import urlConfig from './urlConfig.js'
import urlConfigAddress from './urlConfigAddress.js'

const headers = {}
const baseApi = '/mobile-api'


const request = (option) => {
	headers['Content-Type'] = 'application/json;charset=utf-8'

	let token = uni.getStorageSync('token')
	// 判断是否为白名单
	if (!option.whitelist) {
		if (token && token.length > 0) {
			headers['Authorization'] = 'Bearer ' + token
		}
	}
	let addressCountry =  uni.getStorageSync('addressCountry')
	console.log(addressCountry,'addressCountry')
	
	headers['project_id'] = uni.getStorageSync('projectInfo').id
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseApi + option.url,
			// url: (addressCountry == '中国'?urlConfig:urlConfigAddress) + option.url,
			method: option.method,
			data: option.data,
			dataType: 'json',
			header: headers,
			timeout: option.timeout?option.timeout:60000,
			success: (res) => {
				if (res.statusCode == 200) {
					console.log(addressCountry,'addressCountry','url')
					if (res.data.code == 401) {
						uni.showModal({
							content: '登录状态已过期，请返回登录',
							confirmText: "确定",
							cancelText: "取消"
						}).then(()=>{
							// uni.clearStorageSync()
							uni.removeStorageSync('token')
							uni.navigateTo({
								url: '/pages/login/index'
							})
						})
					} else if (res.data.code == 500) {
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
					} else if (res.data.code == 404) {
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
					}
					resolve(res.data)
				} else {
					uni.showToast({
						title: '系统内部发生错误，请联系管理员',
						icon: 'none'
					})
					resolve(res.data)
				}
			},
			fail: (error) => {
				uni.showToast({
					title: '系统内部发生错误，请联系管理员',
					icon: 'none'
				})
			}
		})
	})
}

export default request
